package com.jt.aop;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.vo.ImageVO;
import com.jt.vo.SysResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 张琪
 * @date 2020/11/30
 * @describe
 */

@RestControllerAdvice           //AOP + 异常处理
@Slf4j
public class SystemException {


    @ExceptionHandler(IOException.class)
    public ImageVO doHandlerIOExceptioin(IOException e) {
        e.printStackTrace();
        return ImageVO.fault();
    }

    /*
        最初的全局异常处理, 不能对jsonp的跨域访问进行正确的处理, 因此需要修改一下
        @ExceptionHandler(RuntimeException.class)
        public SysResult doHandlerRuntimeException(RuntimeException e){
            e.printStackTrace();
            return new SysResult(e);
        }
     */
    @ExceptionHandler(RuntimeException.class)
    public Object doHandleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        log.error(e.getMessage(), e);
        e.printStackTrace();

//        1. 获取请求参数
        String callback = request.getParameter("callback");

//        2. 判断是否为跨域访问
        if (StringUtils.hasLength(callback)) {
            JSONPObject jsonpObject = new JSONPObject(callback, SysResult.fault());
            return jsonpObject;
        }

        return SysResult.fault();
    }
}